﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace ExcelSax.UT {
    public class RessourceLoader {
        public static String ExcelSaxUTAssemblyName = "ExcelSaxUT";

        private Assembly _asm;

        public RessourceLoader(String assemblyName) {
            _asm = null;
            AppDomain curDom = AppDomain.CurrentDomain;
            Assembly[] loadedAssemblies = curDom.GetAssemblies();
            foreach (Assembly a in loadedAssemblies) {
                if ( a.FullName.Contains(assemblyName) ) {
                    _asm = a;
                    break;
                }
            }
            if (_asm == null)
                throw new Exception("impossible de trouver le bon assembly");
        }

        public void GetRessourceToFile(String ressourceName, String fileName) {
            Int32 _BUFF_SIZE_ = 1024;
            BinaryReader br = null;
            BinaryWriter bw = null;
            try {
                if (_asm != null) { // impossible selon le constructeur
                    Stream s = null;
                    s = _asm.GetManifestResourceStream(ressourceName);
                    if (s != null)
                        br = new BinaryReader(s);
                }

                if (br != null) {
                    Byte[] bBuff;
                    bw = new BinaryWriter(File.Open(fileName, FileMode.Create));
                    do {
                        bBuff = br.ReadBytes(_BUFF_SIZE_);
                        if (bBuff.Length > 0) {
                            bw.Write(bBuff);
                        }
                    } while (bBuff.Length > 0);
                } else {
                    throw new Exception(String.Format("ressource [{0}] introuvable", ressourceName));
                }
            } finally {
                if (br != null) br.Close(); br = null;
                if (bw != null) bw.Close(); bw = null;
            }
        }

        public String GetRandomFileName(String ext = null) {
            return System.Guid.NewGuid().ToString() + (String.IsNullOrEmpty(ext) ? String.Empty : ext);
        }

        public String DuplicateFile(String fileName) {
            String destFileName = this.GetRandomFileName(System.IO.Path.GetExtension(fileName)); 
            System.IO.File.Copy(fileName, destFileName);
            return destFileName;
        }
    }
}
